<?php
/**
 * Created by b17
 * 2/5/12 9:34 AM
 */

abstract class G4T_CrudController extends G4T_AdminController
{
    /**
     * @var \Managers\CrudManager
     */
    protected $manager;

    public function init()
    {
        parent::init();
        $this->setManager($this->getManager());
    }

    public function setManager(\Managers\CrudManager $manager)
    {
        $this->manager = $manager;
    }

    public function editAction()
    {
        $id = $this->_request->getParam('id');
        $record = $this->manager->getById($id);

        if (!$record) {
            $this->redirectWhenNotFound($id);
        }
        $form = $this->createFormBuilder()
            ->addField('id', 'hidden')
            ->getForm();
        $form->populate($this->decorate($record));

        $params = $this->_request->getParams();

        if ($this->_request->isPost()) {
            if ($form->isValid($params)) {
                try {
                    $values = $form->getValues();
                    $entity = $this->manager->update($values);
                    $this->redirectWhenSuccess($entity);
                } catch (LogicException $e) {
                    $this->_flashMessenger->addMessage($e->getMessage(), Lib_Flash::ERROR, Lib_Flash::NOW);
                } catch (Exception $e) {
                    $this->handleException($e);
                }
            } else {
                $this->_flashMessenger->addMessage('Please, check input data.', Lib_Flash::ERROR, Lib_Flash::POST);
            }
        }
        $this->view->item = $record;
        $this->view->form = $form;
    }

    public function addAction()
    {
        $form = $this->createFormBuilder()
            ->getForm();
        $form->populate($this->getDefaultValues());

        $params = $this->_request->getParams();

        if ($this->_request->isPost()) {
            if ($form->isValid($params)) {
                try {
                    $values = $form->getValues();
                    $entity = $this->manager->create($values);
                    $this->redirectWhenSuccess($entity);
                } catch (LogicException $e) {
                    $this->_flashMessenger->addMessage($e->getMessage(), Lib_Flash::ERROR, Lib_Flash::NOW);
                } catch (Exception $e) {
                    $this->handleException($e);
                }
            } else {
                $this->_flashMessenger->addMessage('Please, check input data.', Lib_Flash::ERROR, Lib_Flash::POST);
            }
        }
        $this->view->form = $form;
    }

    public function deleteAction()
    {
        $result = $this->manager->delete($this->_getParam('id'));
        if ($result) {
            $this->redirectWhenSuccess();
        } else {
            $this->redirectWhenNotFound($this->_getParam('id'));
        }
    }

    protected function getDefaultValues()
    {
        return array();
    }

    /**
     * Возвращает менеджер для работы с сущностью.
     *
     * @abstract
     * @return \Managers\CrudManager
     */
    protected abstract function getManager();

    /**
     * Возвращает строителя форм для создания форм.
     * @abstract
     * @return \G4T\Form\FormBuilder
     */
    protected abstract function createFormBuilder();

    /**
     * Переход при не найденой сущности.
     * @abstract
     * @param $id
     */
    protected abstract function redirectWhenNotFound($id = null);

    /**
     * Переход при успешном изменении объекта.
     * @abstract
     * @param $entity
     */
    protected abstract function redirectWhenSuccess($entity = null);

    protected function decorate($record)
    {
        return $record;
    }

}
